/**
 * 
 */
package com.etcfg.etlaunch.ui;

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;

import com.etcfg.etlaunch.ETLauncherApplication;
import com.etcfg.etlaunch.ETServer;

@SuppressWarnings("serial")
public class AddServerAction extends AbstractAction {

	/**
	 * 
	 */
	private final MainWindow mainWindow;
	private final ETLauncherApplication etLauncherApplication;
	private String serverIp;

	public AddServerAction(MainWindow mainWindow,
			ETLauncherApplication application) {
		this.mainWindow = mainWindow;
		etLauncherApplication = application;
		putValue(Action.NAME, Messages.getString("AddServerAction.0")); //$NON-NLS-1$
		putValue(Action.SHORT_DESCRIPTION, Messages
				.getString("AddServerAction.1")); //$NON-NLS-1$
		ImageIcon icon = new ImageIcon(getClass().getResource(
				"/com/etcfg/etlaunch/ui/icons/list-add32.png")); //$NON-NLS-1$

		putValue(Action.LARGE_ICON_KEY, icon);
		putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke("0")); //$NON-NLS-1$
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		try {
			if (serverIp == null) {
				serverIp = JOptionPane
						.showInputDialog(
								this.mainWindow.getFrame(),
								Messages.getString("AddServerAction.4"), mainWindow.getClipboardContetnts()); //$NON-NLS-1$
			}
			if (serverIp == null) {
				return;
			}
			if (serverIp.isEmpty()) {
				return;
			}
			ETServer etServer = ETServer.parseServerFromString(serverIp);
			if (etServer == null) {
				JOptionPane.showMessageDialog(this.mainWindow.getFrame(),
						Messages.getString("AddServerAction.6"));
				//$NON-NLS-1$

				return;
			}

			etServer.setServerName(etServer.getIp() + ":" + etServer.getPort()); //$NON-NLS-1$
			ETServer addServer = etLauncherApplication.addServer(etServer);
			JTable serverList = mainWindow.getServerList();
			int indexOf = mainWindow.getListModel().getServers().indexOf(
					addServer);
			int convertRowIndexToView = serverList.getRowSorter()
					.convertRowIndexToView(indexOf);
			serverList.setRowSelectionInterval(convertRowIndexToView,
					convertRowIndexToView);
		} finally {
			serverIp = null;
		}

	}

	public String getServerIp() {
		return serverIp;
	}

	public void setServerIp(String serverIp) {
		this.serverIp = serverIp;
	}

}